package com.ht.api.call.func.impl.wwx;

import java.util.stream.Collectors;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.constant.CustomerLinkStatus;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.util.HtUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 新增获客链接
 * @author asq
 * @createTime 2025年1月13日 22:19:08
 */
@Slf4j
public class WwxCustomerLinkAddFunctionCall implements IFunctionCall {
	@Override
	public String getName() {
		return "新增获客链接";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取登陆用户的数据源
		DataSource ds = me.getDataSource();
		
		// 验证参数
		JSONObject normalParam = HtUtil.revertJson(param);
		checkParam(normalParam);
		String linkName = param.getStr("link_name");
		boolean hasRow = Db.createSqlParser("wx_customer_link").where("link_name", linkName).hasRow(ds);
		if (hasRow) {
			throw new HtException("获客链接已存在：" + linkName);
		}
		
		// 本地数据库新增
		add(ds, normalParam);
		
		return JSONUtil.createObj();
	}

	/**
	 * 新增获客链接
	 * @param ds 数据源
	 * @param param 参数
	 */
	private void add(DataSource ds, JSONObject param) {
		Entity wxCustomerLink = Db.createEntity("wx_customer_link");
		wxCustomerLink.set("appid", param.getStr("appid"));
		wxCustomerLink.set("link_name", param.getStr("link_name"));
		wxCustomerLink.set("status", CustomerLinkStatus.DISABLED);
		if (param.containsKey("skip_verify")) {
			wxCustomerLink.set("skip_verify", param.getBool("skip_verify") ? 1 : 0);
		}
		if (param.containsKey("priority_option")) {
			JSONObject priorityOption = param.getJSONObject("priority_option");
			wxCustomerLink.set("priority_type", priorityOption.getInt("priority_type"));
			
			JSONArray priorityUseridList = priorityOption.getJSONArray("priority_userid_list");
			wxCustomerLink.set("priority_userid_list", priorityUseridList.toString());
			if (!priorityUseridList.isEmpty()) {
				String hashCodes = priorityUseridList.stream().map(s -> String.valueOf(Math.abs(s.hashCode())))
						.collect(Collectors.joining(","));
				wxCustomerLink.set("priority_userid_list_hash", hashCodes);
			}
		}
		wxCustomerLink.set("click_link_customer_cnt", 0);
		wxCustomerLink.set("new_customer_cnt", 0);
		wxCustomerLink.set("error", 0);
		
		Db.insert(ds, wxCustomerLink);
	}

	/**
	 * 验证参数合法性
	 * @param param
	 */
	private void checkParam(JSONObject param) {
		if (StrUtil.isBlank(param.getStr("link_name"))) {
			throw new HtException("link_name不能为空~");
		}
		if (StrUtil.isBlank(param.getStr("appid"))) {
			throw new HtException("appid不能为空~");
		}
	}
}
